﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using wenku8.MyEventArgs;
using wenku8.Entity;
using wenku8.Exceptions;
using wenku8.Parser;
using wenku8.Xamls;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using wenku8.Xamls.SettingPages;

// https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板

namespace wenku8
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public static TextBlock TitleTextBlock { get; set; }
        public static SplitView MainSplitView { get; set; }

        public static event EventHandler ReturnTopEvent;
        public static event EventHandler PostCommentEvent;

        private static ProgressRing MainProgressRing { get; set; }
        private static Button ReturnTopButton;

        private string currentBookClassification;


        public MainPage()
        {
            this.InitializeComponent();

            MainSplitView = menuSplitView;
            TitleTextBlock = titleTextBlock;
            MainProgressRing = progressBar;
            ReturnTopButton = returnTopButton;

            contentFrame.Navigated += OnNavigated;
            SystemNavigationManager.GetForCurrentView().BackRequested += BackRequested;
            this.AddHandler(KeyDownEvent, new KeyEventHandler(OnBackKeyDown), true);
            InitializeHttpClient();
        }

        // 初始化 HttpClient
        private async void InitializeHttpClient()
        {
            try {
                if (await HTMLParser.InitializeAsync())
                    contentFrame.Navigate(typeof(BookItemsPage), new Button { Name = "updatedNovelsButton" });
                else
                    PopMessageDialog("初始化失败！");
                //contentFrame.Navigate(typeof(SettingPage));
            }
            catch (UserNotExists) {
                contentFrame.Navigate(typeof(SignInPage));
            }
            catch (Exception) {
                PopMessageDialog("网络或用户名、密码错误！");
            }
        }

        /// <summary>
        /// 处理键盘退格键，返回上一页
        /// </summary>
        private void OnBackKeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key is Windows.System.VirtualKey.Back && contentFrame.CanGoBack) {
                MainProgressRing.IsActive = true;
                MainProgressRing.Visibility = Visibility.Visible;
                contentFrame.GoBack();
            }
        }

        /// <summary>
        /// 弹窗显示消息
        /// </summary>
        /// <param name="message">消息内容</param>
        public static async void PopMessageDialog(string message)
        {
            var dialog = new ContentDialog()
            {
                Content = message,
                IsPrimaryButtonEnabled = true,
                PrimaryButtonText = "确定",
                FullSizeDesired = false,
                Background = new Windows.UI.Xaml.Media.SolidColorBrush(Color.FromArgb(191, 243, 243, 248)),
                BorderThickness = new Thickness(0.0)
            };
            await dialog.ShowAsync();
        }

        /// <summary>
        /// 汉堡按钮事件处理 控制SplitView.Pane的开关
        /// </summary>
        private void MenuButton_Click(object sender, RoutedEventArgs e)
        {
            menuSplitView.IsPaneOpen = !menuSplitView.IsPaneOpen;
        }

        /// <summary>
        /// 处理书籍种类按钮的点击事件
        /// </summary>
        private void BookClassificationButton_Click(object sender, RoutedEventArgs e)
        {
            if (Window.Current.Bounds.Width <= 1200) {
                menuSplitView.IsPaneOpen = false;
            }
            if ((sender as Button).Name != currentBookClassification) {
                MainProgressRing.IsActive = true;
                MainProgressRing.Visibility = Visibility.Visible;
                contentFrame.Navigate(typeof(BookItemsPage), sender);
                contentFrame.BackStack.Clear();
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                currentBookClassification = (sender as Button).Name;
            }
        }

        /// <summary>
        /// 设置 按钮事件处理
        /// </summary>
        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            MainPage.EnableProgressRing();
            contentFrame.Navigate(typeof(SettingPage));
        }

        /// <summary>
        /// 账户 按钮事件处理
        /// </summary>
        private void AccountButton_Click(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// 标题栏返回按钮事件响应
        /// </summary>
        private void BackRequested(object sender, BackRequestedEventArgs e)
        {
            if (contentFrame.CanGoBack) {
                contentFrame.GoBack();
            }
            e.Handled = true;
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                contentFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
        }

        /// <summary>
        /// 控制标题栏返回键的可见性
        /// </summary>
        private void OnNavigated(object sender, NavigationEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = ((Frame)sender).CanGoBack ?
                AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;

            var currentPageType = contentFrame.SourcePageType;
            if (currentPageType == typeof(BookDetalsPage) || currentPageType == typeof(RepliesPage)) {
                EnableReturnTopButton();
                //addCommentButton.IsEnabled = true;
                //addCommentButton.Visibility = Visibility.Visible;
            }
            else {
                DisableReturnTopButton();
                //addCommentButton.IsEnabled = false;
                //addCommentButton.Visibility = Visibility.Collapsed;
            }

        }

        #region 控制控件的可见性

        /// <summary>
        /// 显示进度环
        /// </summary>
        internal static void EnableProgressRing()
        {
            if (MainProgressRing != null) {
                MainProgressRing.IsActive = true;
                MainProgressRing.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 隐藏进度环
        /// </summary>
        internal static void DisableProgressRing()
        {
            if (MainProgressRing != null) {
                MainProgressRing.IsActive = false;
                MainProgressRing.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 显示返回顶部按钮
        /// </summary>
        internal static void EnableReturnTopButton()
        {
            ReturnTopButton.IsEnabled = true;
            ReturnTopButton.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 隐藏返回顶部按钮
        /// </summary>
        internal static void DisableReturnTopButton()
        {
            ReturnTopButton.IsEnabled = false;
            ReturnTopButton.Visibility = Visibility.Collapsed;
        }

        #endregion

        /// <summary>
        /// 返回顶部按钮点击事件处理
        /// </summary>
        private void ReturnTopButton_Click(object sender, RoutedEventArgs e) => ReturnTopEvent(null, null);

        /// <summary>
        /// 添加评论按钮点击事件处理
        /// </summary>
        private void AddCommentButton_Click(object sender, RoutedEventArgs e)
        {
            commentGrid.Visibility = Visibility.Visible;
        }

        private void PostButton_Click(object sender, RoutedEventArgs e)
        {
            PostCommentEvent(null, new CommentEventArgs(commentTextBox.Text));
            commentGrid.Visibility = Visibility.Collapsed;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            commentGrid.Visibility = Visibility.Collapsed;
        }
    }
}
